/*
 * @lc app=leetcode.cn id=25 lang=cpp
 *
 * [25] K 个一组翻转链表
 */

// @lc code=start
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */

class Solution
{
public:
  ListNode* reverseKGroup(ListNode* head, int k)
  {
    ListNode* dummy = new ListNode(-1);
    ListNode *tmp = dummy, *left = head, *right = head;

    while (left) {
      int len = 1;
      while (len < k && right->next != nullptr) {
        right = right->next;
        ++len;
      }
      if (len == k) {
        ListNode* new_left = right->next;
        ListNode *pre = nullptr, *cur = left;
        while (cur != new_left) {
          ListNode* next = cur->next;
          cur->next = pre;
          pre = cur;
          cur = next;
        }
        tmp->next = pre;
        tmp = left;
        left = right = new_left;
      }
      else {
        tmp->next = left;
        break;
      }
    }

    return dummy->next;
  }
};
// @lc code=end